/**
 * @description 岗位管理
 * @author 李艳
 */
import React, {Component} from "react";
import {deletePosition, findByOrganizationId, savePosition} from "./PositionService";
import {Button, Col, Form, Input, message, Modal, Row} from "antd";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import SimpleTable from "../../../commons/components/SimpleTable";
import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import PositionConfigTabsView from "./PositionConfigTabsView";
import {listAllTree} from "../Organization/OrganizationService";
import EditPositionModal from "./EditPositionModal";
import StandardTree from "../../../commons/components/StandardTree";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import {rowGutter} from "../../../configs/DefaultConfig";
import DetailCard from "../../../commons/components/DetailCard";
import CheckAuth from "../../../commons/components/CheckAuth";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";

const Search = Input.Search;
const confirm = Modal.confirm;

class PositionView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "岗位管理"}];
    this.state = {
      treeData: [],
      searchValue: "",
      tableSearchValue: "",
      tableData: [],
      findResultData: [],
      treeSelectedKeys: [],
      selectedNode: {},
      loading: false,
      tableSelectRow: [],
      modalVisible: false,
      confirmLoading: false,
      isAdd: true,
      pathName: "岗位",
    }
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  };

  componentWillMount() {
    this.getTreeData()
  };

  //网络请求树控件数据
  getTreeData = (param) => {
    this.props.show();
    listAllTree(param).then((result) => {
      this.setState({
        treeData: result,
      });
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  //网络请求table控件数据
  listPositionByOrgId = (param) => {
    this.setState({loading: true});
    findByOrganizationId(param).then((result) => {
      this.setState({
        tableData: result, tableSelectRow: [], tableSearchValue: ""
      });
    }).catch(err => {
    }).finally(() => {
      this.setState({loading: false});
    });
  };

  //树节点选择触发
  onTreeSelect = (selectedKeys, selectedNodes) => {
    this.setState({treeSelectedKeys: selectedKeys});
    if (selectedNodes[0]) {
      this.setState({selectedNode: selectedNodes[0]});
      let params = {'organizationId': selectedNodes[0].id ? selectedNodes[0].id : ""};
      this.listPositionByOrgId(params);
      this.setState({pathName: selectedNodes[0].name ? selectedNodes[0].name : '岗位'});
    }
  };

  handleTableSearch = (value) => {
    searchListByKeyWithTag(this.state.tableData, {keyword: value}, ["code", "name", "positionCategory.name"]).then(res => {
      this.setState({tableData: res, tableSearchValue: value})
    })
  };
  onAddRuleClick = () => {
    if (this.state.selectedNode && JSON.stringify(this.state.selectedNode) !== "{}") {
      this.setState({
        modalVisible: true,
        isAdd: true
      })
    } else {
      message.error('请选择组织机构')
    }

  };
  onEditPositionClick = (record) => {
    this.setState({rightEditData: record});
    this.setState({
      modalVisible: true,
      isAdd: false
    })
  };
  //新增或编辑点击确定按钮事件
  handleEditPosition = () => {
    //表单数据同步
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, modalVisible: true});
          if (this.state.isAdd) {
            delete values.id
          }
          savePosition(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求table数据刷新本地数据
              let params = {'organizationId': this.state.selectedNode.id};
              this.listPositionByOrgId(params);
              this.setState({confirmLoading: false, modalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  handleModalCancel = () => {
    this.setState({modalVisible: false})
  };

  onDeletePositionClick = (record) => {
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deletePosition(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            let params = {'organizationId': thiz.state.selectedNode.id};
            thiz.listPositionByOrgId(params);
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });

  };
  onTableSelectRow = (tableSelectRow) => {
    this.setState({tableSelectRow});
  };
  judgeSelected = () => {
    if (!this.state.tableSelectRow[0]) {
      message.error('请选择一行数据！');
      return false;
    }
    return true;
  };

  onPositionConfigClick = () => {
    if (!this.judgeSelected()) return;
    this.setDisplay(true)
  };

  setDisplay = (display) => {
    this.setState({isPositionConfig: display})
  };
  getPathData = () => {
    const {isPositionConfig, tableSelectRow} = this.state;
    if (isPositionConfig) {
      const path = [{name: `岗位【${tableSelectRow[0] ? tableSelectRow[0].name : ""}】`}, {name: "配置"}];
      return [...this.initPath, ...path];
    } else {
      return null;
    }
  };
  getExtra = () => {
    const {isPositionConfig} = this.state;
    if (isPositionConfig) {
      return [
        <Button key={"return"} onClick={() => this.setDisplay(false)}>返回</Button>
      ]
    }
    return null;
  };

  render() {
    const columns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-YHGL-ZZJG-EDITPOSITION">
                <a className={'row-operator-item'} onClick={() => this.onEditPositionClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-YHGL-ZZJG-DELETEPOSITION">
                <a className={'row-operator-item'} onClick={() => this.onDeletePositionClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 120
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: '岗位类别',
        dataIndex: 'positionCategory.name',
        width: 200
      }
    ];
    const title = () => {
      return [
        <CheckAuth key='addRule' operateCode="BASIC-YHGL-ZZJG-ADDPOSITION">
          <Button key="addRule" className={"primaryButton"} type={"primary"}
                  onClick={this.onAddRuleClick}>新增</Button>
        </CheckAuth>,
        <Button.Group key={"elseButton"}>
          <CheckAuth key='config' operateCode="BASIC-YHGL-ZZJG-CONFIGPOSITION">
            <Button onClick={this.onPositionConfigClick}>配置</Button>
          </CheckAuth>
        </Button.Group>
      ]
    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入关键字查询"
          onSearch={value => this.handleTableSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    return (
      <HeadBreadcrumb
        pathData={this.getPathData()}
        rightExtra={this.getExtra()}
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{height: "100%", display: this.state.isPositionConfig ? "none" : "block"}}>
          {/*左边的树状控件*/}
          <Col span={10} style={{height: "100%"}}>
            <DetailCard title="组织机构" style={{height: "100%"}}>
              <StandardTree
                onSelect={this.onTreeSelect}
                dadaSource={this.state.treeData}/>
            </DetailCard>
          </Col>
          {/*右边的表格控件*/}
          <Col span={14} style={{height: "100%"}}>
            <DetailCard title={this.state.pathName} style={{height: "100%"}} className={"child-card"}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{title()}</div>
                <div className={'tbar-search-box'}>{search()}</div>
              </div>
              <SimpleTable
                inCard={true}
                data={this.state.tableSearchValue ? this.state.tableData.filter(item => item.tag === true) : this.state.tableData}
                columns={columns}
                loading={this.state.loading}
                onSelectRow={this.onTableSelectRow}
                rowsSelected={this.state.tableSelectRow}
              />
            </DetailCard>

            <EditPositionModal
              modalVisible={this.state.modalVisible}
              confirmLoading={this.state.confirmLoading}
              handleOk={this.handleEditPosition}
              handleCancel={this.handleModalCancel}
              onRef={this.onModalRef}
              defaultValue={this.state.rightEditData ? this.state.rightEditData : {}}
              selectedNode={this.state.selectedNode}
              isAdd={this.state.isAdd}
            />
          </Col>
        </Row>
        {
          this.state.isPositionConfig ? <PositionConfigTabsView
            positionInfo={this.state.tableSelectRow[0] ? this.state.tableSelectRow[0] : {}}
            setDisplay={this.setDisplay}/> : null
        }
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
PositionView = Form.create()(PositionView);
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(PositionView))
